from flask import views, render_template, request, url_for, \
    redirect, Blueprint, make_response
from sqlalchemy.exc import SQLAlchemyError
from mysql_config import db
from models import User
from models import UserOrder
from models import Car
from models import Location
from result import Result
from result_code import Code

import smtplib
from pathlib import Path
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


order = Blueprint('order_control', __name__)


@order.route('/order/<order_id>', methods=['GET'])
def order_by_oid_query(order_id):
    res = UserOrder.query.filter(UserOrder.order_id == order_id).first()
    if res is None:
        resp = vars(Result(Code.GET_ERR.value, None, "未查询到结果"))
        return resp
    else:
        user_dic = vars(res)
        del user_dic['_sa_instance_state']
        resp = vars(Result(Code.GET_ERR.value, user_dic, "单个订单信息"))
        return resp


@order.route('/orders/<uid>', methods=['GET'])
def order_by_uid_query(uid):
    orders = UserOrder.query.filter(UserOrder.s_uid == uid).all()
    if len(orders) == 0:
        resp = vars(Result(Code.GET_ERR.value, None, "未查询到结果"))
        return resp
    else:
        orders_list = []
        for order in orders:
            order_dic = vars(order)
            del order_dic['_sa_instance_state']
            orders_list.append(order_dic)
            print(orders_list)
        resp = vars(Result(Code.GET_ERR.value, orders_list, "订单信息列表"))
        return resp


@order.route('/order/query', methods=['POST'])
def order_query():
    order_id = request.json.get("order_id")
    username = request.json.get("username")
    state = request.json.get("state")

    # 根据3个条件一起查询
    if order_id != '' and username != '' and state != -1:
        res = UserOrder.query.filter(UserOrder.order_id == order_id, UserOrder.s_name == username, UserOrder.state == state).first()
        if res is None:
            resp = vars(Result(Code.GET_ERR.value, None, "未查询到结果"))
            return resp
        else:
            user_dic = vars(res)
            del user_dic['_sa_instance_state']
            resp = vars(Result(Code.GET_ERR.value, [user_dic], "查询到结果"))
            return resp

    # 只根据order_id查询
    if order_id != '' and username == '' and state == -1:
        res = UserOrder.query.filter(UserOrder.order_id == order_id).first()
        if res is None:
            resp = vars(Result(Code.GET_ERR.value, None, "未查询到结果"))
            return resp
        else:
            user_dic = vars(res)
            del user_dic['_sa_instance_state']
            resp = vars(Result(Code.GET_ERR.value, [user_dic], "查询到结果"))
            return resp

    # 只根据username查询
    if username != '' and order_id == '' and state == -1:
        res = UserOrder.query.filter(UserOrder.s_name == username).all()
        if len(res) == 0:  # 查询无结果
            resp = vars(Result(Code.GET_ERR.value, None, "未查询到结果"))
            return resp
        else:
            orders_list = []
            for res_one in res:
                res_one_dic = vars(res_one)
                del res_one_dic['_sa_instance_state']
                orders_list.append(res_one_dic)
            resp = vars(Result(Code.GET_ERR.value, orders_list, "查询到结果"))
            return resp

    # 只根据state查询
    if state != -1 and order_id == '' and username == '':
        res = UserOrder.query.filter(UserOrder.state == state).all()
        if len(res) == 0:  # 查询无结果
            resp = vars(Result(Code.GET_ERR.value, None, "未查询到结果"))
            return resp
        else:
            orders_list = []
            for res_one in res:
                res_one_dic = vars(res_one)
                del res_one_dic['_sa_instance_state']
                orders_list.append(res_one_dic)
            resp = vars(Result(Code.GET_ERR.value, orders_list, "查询到结果"))
            return resp
    
    # 根据username和state查询
    if username != '' and state != -1 and order_id == '':
        res = UserOrder.query.filter(UserOrder.state == state, UserOrder.s_name == username).all()
        if len(res) == 0:  # 查询无结果
            resp = vars(Result(Code.GET_ERR.value, None, "未查询到结果"))
            return resp
        else:
            orders_list = []
            for res_one in res:
                res_one_dic = vars(res_one)
                del res_one_dic['_sa_instance_state']
                orders_list.append(res_one_dic)
            resp = vars(Result(Code.GET_ERR.value, orders_list, "查询到结果"))
            return resp

    # 根据order_id和username查询
    if order_id != '' and username != '' and state == -1:
        res = UserOrder.query.filter(UserOrder.order_id == order_id, UserOrder.s_name == username).first()
        if res is None:
            resp = vars(Result(Code.GET_ERR.value, None, "未查询到结果"))
            return resp
        else:
            user_dic = vars(res)
            del user_dic['_sa_instance_state']
            resp = vars(Result(Code.GET_ERR.value, [user_dic], "查询到结果"))
            return resp

    # 根据order_id和state查询
    if order_id != '' and username == '' and state != -1:
        res = UserOrder.query.filter(UserOrder.order_id == order_id, UserOrder.state == state).first()
        if res is None:
            resp = vars(Result(Code.GET_ERR.value, None, "未查询到结果"))
            return resp
        else:
            user_dic = vars(res)
            del user_dic['_sa_instance_state']
            resp = vars(Result(Code.GET_ERR.value, [user_dic], "查询到结果"))
            return resp

    return vars(Result(Code.GET_ERR.value, None, "未查询到结果"))


@order.route('/order', methods=['POST'])
def order_submit():
    s_uid = request.json.get("s_uid")
    s_name = request.json.get("s_name")
    s_tel = request.json.get("s_tel")
    r_name = request.json.get("r_name")
    r_tel = request.json.get("r_tel")
    item_num = request.json.get("item_num")
    item_type = request.json.get("item_type")
    item_weight = request.json.get("item_weight")
    remark = request.json.get("remark")
    begin_lnglat = request.json.get("begin_lnglat")
    end_lnglat = request.json.get("end_lnglat")

    s_addr_pr = request.json.get("s_addr_pr")
    s_addr_city = request.json.get("s_addr_city")
    s_addr_town = request.json.get("s_addr_town")
    s_addr_district = request.json.get("s_addr_district")
    s_addr_street = request.json.get("s_addr_street")

    r_addr_pr = request.json.get("r_addr_pr")
    r_addr_city = request.json.get("r_addr_city")
    r_addr_town = request.json.get("r_addr_town")
    r_addr_district = request.json.get("r_addr_district")
    r_addr_street = request.json.get("r_addr_street")

    # 空值处理
    if isinstance(s_addr_city, list):
        if len(s_addr_city) == 0:
            s_addr_city = None

    if isinstance(r_addr_city, list):
        if len(r_addr_city) == 0:
            r_addr_city = None

    r_user = User.query.filter(User.tel == r_tel).first()
    if r_user is None:  # 收件人是未注册的用户
        order = UserOrder(s_uid=s_uid, s_name=s_name, s_tel=s_tel, r_name=r_name,
                          r_tel=r_tel, item_num=item_num, item_type=item_type,
                          item_weight=item_weight, remark=remark, begin_lnglat=begin_lnglat,
                          end_lnglat=end_lnglat, state=0, s_addr_pr=s_addr_pr, s_addr_city=s_addr_city,
                          s_addr_town=s_addr_town, s_addr_district=s_addr_district, s_addr_street=s_addr_street,
                          r_addr_pr=r_addr_pr, r_addr_city=r_addr_city, r_addr_town=r_addr_town,
                          r_addr_district=r_addr_district, r_addr_street=r_addr_street
                          )
        db.session.add(order)
        db.session.commit()
        resp = vars(Result(Code.UPDATE_OK.value, None, '订单提交成功'))
        return resp
    else:  # 收件人是已注册的用户，在订单中记录收件人的uid
        r_uid = r_user.uid
        order = UserOrder(s_uid=s_uid, s_name=s_name, s_tel=s_tel, r_name=r_name, r_uid=r_uid,
                          r_tel=r_tel, item_num=item_num, item_type=item_type,
                          item_weight=item_weight, remark=remark, begin_lnglat=begin_lnglat,
                          end_lnglat=end_lnglat, state=0, s_addr_pr=s_addr_pr, s_addr_city=s_addr_city,
                          s_addr_town=s_addr_town, s_addr_district=s_addr_district, s_addr_street=s_addr_street,
                          r_addr_pr=s_addr_pr, r_addr_city=s_addr_city, r_addr_town=s_addr_town,
                          r_addr_district=s_addr_district, r_addr_street=s_addr_street
                          )
        db.session.add(order)
        db.session.commit()
        resp = vars(Result(Code.UPDATE_OK.value, None, '订单提交成功'))
        return resp


@order.route('/order/pass/<order_id>', methods=['GET'])
def order_pass(order_id):
    res_order = UserOrder.query.filter(UserOrder.order_id == order_id).first()
    if res_order is None:
        return {'msg': '操作失败'}
    try:
        res_order.state = 1
        db.session.commit()
        return {'msg': '操作成功'}
    except SQLAlchemyError as e:
        db.session.rollback()
        return {'msg': '操作失败'}


@order.route('/order/state', methods=['POST'])
def change_order_state():
    oid = request.json.get("oid")
    state = int(request.json.get("state"))
    if state < 0 or state > 6:  # 0-5
        return {'code': -1, 'msg': 'state不合法'}
    res_order = UserOrder.query.filter(UserOrder.order_id == oid).first()
    if res_order is None:
        return {'code': -2, 'msg': 'oid错误'}
    else:
        res_order.state = state
        db.session.commit()
        return {'code': 0, 'msg': '操作成功'}


@order.route('/warning', methods=['POST'])
def warning():
    cid = request.json.get("cid")
    oid = request.json.get("oid")
    w = request.json.get("w")
    res_car = Car.query.filter(Car.car_id == cid).first()
    res_car.car_state = w
    db.session.commit()

    res_order = UserOrder.query.filter(UserOrder.order_id == oid).first()
    suid = res_order.s_uid
    res_user = User.query.filter(User.uid == suid).first()
    user_email = res_user.mail

    account = '2486205137@qq.com'  # 发送人的邮箱账号
    password = 'piruknmsctibeadb'  # smtp口令
    
    if w == '2':
        # print(f"{account}\n{password}\n{reciAccount}")
        try:
            # 构建邮件
            msg = MIMEMultipart()
            subject = Header('配送小车出现异常', 'utf-8').encode()
            msg['Subject'] = subject  # 邮件主题
            msg['From'] = account
            msg['TO'] = user_email
            content = MIMEText('配送小车出现了异常，请及时前往配送平台监控面板进行查看！')
            msg.attach(content)
            # print(msg.as_string())

            smtpServer = 'smtp.qq.com'
            serverPort = 465

            smtpObj = smtplib.SMTP_SSL(smtpServer, serverPort)
            smtpObj.ehlo()
            smtpObj.login(account, password)
            smtpObj.sendmail(account, user_email, msg.as_string())
            smtpObj.quit()
        except Exception:
            print("发送邮件失败")
        
    return {'msg': 'warning_ok'}


@order.route('/order/car/<oid>', methods=['GET'])
def get_car_id(oid):
    res_order = UserOrder.query.filter(UserOrder.order_id == oid).first()
    if res_order is None:
        return{ 'data': None, 'msg': '查询失败'}
    car_id = res_order.car_id
    return {'data': car_id, 'msg': '查询成功'}

